package com.jz.netthings.engine.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jy.faceValidate.utils.FaceValidateUtils;
import com.jz.netthings.appengine.baseData.AllotData;
import com.jz.netthings.appengine.baseData.MachineData;
import com.jz.netthings.appengine.baseData.ProviderData;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.mapper.ProviderDataMapper;
import com.jz.netthings.appengine.mapper.ProviderInfoMapper;
import com.jz.netthings.appengine.queue.MachineMgr;
import com.jz.netthings.appengine.queue.ProviderQueue;
import com.jz.netthings.appengine.support.BeanSupport;
import com.jz.netthings.application.base.bean.ProviderAddressAllowance;
import com.jz.netthings.application.base.mapper.mysql.ProviderAddressAllowanceMapper;
import com.jz.netthings.application.bodyCheck.bean.BodyCheck;
import com.jz.netthings.application.bodyCheck.mapper.mysql.BodyCheckMapper;
import com.jz.netthings.application.heatseal.bean.BoxConf;
import com.jz.netthings.application.heatseal.bean.HeatSeal;
import com.jz.netthings.application.heatseal.mapper.mysql.BoxConfMapper;
import com.jz.netthings.application.heatseal.mapper.mysql.HeatSealMapper;
import com.jz.netthings.application.providerAllot.bean.ProviderAllot;
import com.jz.netthings.application.providerAllot.mapper.mysql.ProviderAllotMapper;
import com.jz.netthings.application.providerCollection.bean.ProviderCollection;
import com.jz.netthings.application.providerCollection.mapper.mysql.ProviderCollectionMapper;
import com.jz.netthings.application.providerCost.bean.ProviderCost;
import com.jz.netthings.application.providerCost.bean.ProviderTimesAllowance;
import com.jz.netthings.application.providerCost.mapper.mysql.ProviderCostMapper;
import com.jz.netthings.application.providerCost.mapper.mysql.ProviderTimesAllowanceMapper;
import com.jz.netthings.application.providerCreate.bean.ProviderXp;
import com.jz.netthings.application.providerCreate.bean.ProviderZw;
import com.jz.netthings.application.providerCreate.mapper.mysql.ProviderXpMapper;
import com.jz.netthings.application.providerCreate.mapper.mysql.ProviderZwMapper;
import com.jz.netthings.application.providerCreate.service.ProviderInfoService;
import com.jz.netthings.application.providerReg.bean.ProviderReg;
import com.jz.netthings.application.providerReg.mapper.mysql.ProviderRegMapper;
import com.jz.netthings.application.providerXqdy.bean.ProviderXqdyph;
import com.jz.netthings.application.providerXqdy.bean.ProviderXqdyqd;
import com.jz.netthings.application.providerXqdy.mapper.mysql.ProviderXqdyphMapper;
import com.jz.netthings.application.providerXqdy.mapper.mysql.ProviderXqdyqdMapper;
import com.jz.netthings.application.sample.bean.PlasmaSamples;
import com.jz.netthings.application.sample.mapper.PlasmaSamplesMapper;
import com.jz.netthings.application.upload.service.UploadService;
import com.jz.netthings.bean.system.JyCode;
import com.jz.netthings.bean.system.JyUser;
import com.jz.netthings.engine.bean.*;
import com.jz.netthings.engine.service.ClientService;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.netty.protocol.bean.*;
import com.jz.netthings.netty.support.ClientType;
import com.jz.netthings.netty.utils.NettyMsgHelper;
import com.jz.netthings.system.mapper.mysql.JyCodeMapper;
import com.jz.netthings.system.mapper.mysql.JyUserMapper;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import io.netty.channel.ChannelHandlerContext;
import jdk.nashorn.internal.objects.annotations.Where;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("clientService")
public class ClientServiceImpl implements ClientService {

    Logger logger = LoggerFactory.getLogger(getClass());
    private static final long dayTime = 24 * 60 * 60 * 1000;
    @Autowired
    RedisTemplate<Object, Object> objectRedisTemplate;
    @Autowired
    ProviderInfoMapper providerInfoMapper;
    @Autowired
    JyCodeMapper jyCodeMapper;
    @Autowired
    UploadService uploadService;
    @Autowired
    ProviderCollectionMapper providerCollectionMapper;
    @Autowired
    ProviderInfoService providerInfoService;
    @Autowired
    ProviderXpMapper providerXpMapper;
    @Autowired
    ProviderRegMapper providerRegMapper;
    @Value("${ly.upload.baseUrl}")
    String photoUrl;
    @Value("${engine.faceValidate.sourcesPath}")
    private String sourcePath;
    @Value("${engine.faceValidate.tempPath}")
    private String tempPath;
    @Autowired
    ProviderDataMapper providerDataMapper;
    @Autowired
    BodyCheckMapper bodyCheckMapper;
    @Autowired
    ProviderQueue providerQueue;
    @Autowired
    PlasmaSamplesMapper plasmaSamplesMapper;
    @Autowired
    ProviderCostMapper providerCostMapper;
    @Autowired
    ProviderXqdyqdMapper providerXqdyqdMapper;
    @Autowired
    ProviderAddressAllowanceMapper providerAddressAllowanceMapper;
    @Autowired
    ProviderZwMapper providerZwMapper;
    @Autowired
    ProviderAllotMapper providerAllotMapper;
    @Autowired
    ProviderXqdyphMapper providerXqdyphMapper;
    @Autowired
    HeatSealMapper heatSealMapper;
    @Autowired
    BoxConfMapper boxConfMapper;
    @Autowired
    JyUserMapper jyUserMapper;
    @Autowired
    ProviderTimesAllowanceMapper providerTimesAllowanceMapper;
    @Override
    public LoginResponsePacket clientUserLogin(LoginRequestPacket packet) {

        LoginResponsePacket responsePacket = new LoginResponsePacket();

        logger.info("客户端登录认证...");
        if (packet != null) {
            String username = packet.getUsername();
            ClientType clientType = packet.getClientType();
            logger.info("请求登录用户：" + username + "，客户端类型：" + clientType + "，客户端编号：" + packet.getClientCode());

            responsePacket.setSuccess(true);
            responsePacket.setName(username);
            responsePacket.setUsername(username);
            responsePacket.setUserId(packet.getUserId());
            responsePacket.setUserPhoto(Base64.getEncoder().encodeToString("asdfasdfasdf".getBytes()));

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            responsePacket.setUuid(uuid);

            logger.info("认证成功，存放缓存...");
            AdscmBaseUtils.getInstance().addObjToRedis(uuid, responsePacket, objectRedisTemplate);
            //如果是分配客户端登录，则将上下文放到缓存中去
            if (packet.getClientType() == ClientType.ALLOT) {
                synchronized (MachineMgr.getInstance()) {
                    List<ChannelHandlerContext> allotCtxs = MachineMgr.getInstance().getAllotCtxs();
                    allotCtxs.add(packet.getCtx());
                }
            }


        } else {
            responsePacket.setSuccess(false);
            responsePacket.setReason("登录信息为Null，登录失败...");
        }

        return responsePacket;
    }

    @Override
    public FaceValidateResponsePacket clientFaceValidate(FaceValidateRequestPacket packet) {
        logger.info("开始进行【" + packet.getIdCard() + "】的人脸认证...");

        FaceValidateResponsePacket responsePacket = new FaceValidateResponsePacket(packet.getIdCard(), 0f);


        String[] path = this.getImgsPath(packet.getIdCard(), packet.getPhoto());


        if (path[0] != null && path[1] != null) {
            float result = FaceValidateUtils.validateImg(path[0], path[1]);
            responsePacket.setThreshold(result);
        }
        return responsePacket;
    }

    /**
     * 根据身份证或者卡号查询浆员的信息
     * 登记的查询浆员信息
     *
     * @param idCard
     * @return BloodUser
     * @throws AdscmSystemException
     */
    @Override
    public BloodUser providerReqRegisterMsg(String idCard) throws AdscmSystemException {
        BloodUser bloodUser = new BloodUser();
        if (idCard == null || "".equals(idCard)) {
            throw new AdscmSystemException("没有获取到身份信息，请确认身份证是否消磁或者输入的卡号或者身份证号是否正确！");
        }
        //根据idCard 查询浆员信息
        ProviderInfo providerInfo = new ProviderInfo();
        Wrapper<ProviderInfo> idNoWrapper = new EntityWrapper<>();
        idNoWrapper.eq("idNo", idCard);
        List<ProviderInfo> providerInfos = providerInfoMapper.selectList(idNoWrapper);
        if (providerInfos != null && providerInfos.size() > 0) {
            providerInfo = providerInfos.get(0);
        } else {
            //根据卡号查询这个浆的信息
            Wrapper<ProviderInfo> idCardWrapper = new EntityWrapper<>();
            idCardWrapper.eq("cardId", idCard);
            List<ProviderInfo> idCardProviderInfo = providerInfoMapper.selectList(idCardWrapper);
            if (idCardProviderInfo != null && idCardProviderInfo.size() > 0) {
                providerInfo = idCardProviderInfo.get(0);
            } else {
                throw new AdscmSystemException("未从服务端获取到身份信息！");
            }
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo, null)) {
            //浆员状态是否被永久拒绝
            Integer providerState = providerInfo.getProviderState();
            if (2 == providerState) {
                throw new AdscmSystemException("您已经不能献浆了");
            }
            //暂时拒绝,登记之后变成正常
            if (1 == providerState) {
                providerInfo.setProviderState(0);
            }
            //根据身份证算出年龄
            String birthDay = providerInfo.getIdNo().substring(6, 14);
            Date date = AdscmDateUtils.parseDate2(birthDay);
            int age = AdscmDateUtils.getAge(date);
            if (age >= 56) {
                throw new AdscmSystemException("您的年龄是56周岁以上，不能登记！");
            } else if (age < 18) {
                throw new AdscmSystemException("您的年龄是18周岁以下，不能登记！");
            }
            providerInfo.setAge(age);
            providerInfoMapper.updateById(providerInfo);
            //最近一次采浆日期
            Date lastdate = null;
            //采浆量
            int cjl = 0;
            //在采浆记录中获取到最后一次采浆的采浆量与日期
            Wrapper<ProviderCollection> providerCollectionWrapper = new EntityWrapper<>();
            providerCollectionWrapper.eq("providerNo", providerInfo.getId());
            providerCollectionWrapper.eq("isDeal", "1");
            providerCollectionWrapper.orderBy("createTime", false);
            List<ProviderCollection> providerCollections = providerCollectionMapper.selectList(providerCollectionWrapper);
            if (providerCollections != null && providerCollections.size() > 0) {
                ProviderCollection providerCollection = providerCollections.get(0);
                if (AdscmBaseUtils.getInstance().isNotEmpty(providerCollection.getCreateTime(), null)) {
                    lastdate = providerCollection.getCreateTime();
                }
                if (AdscmBaseUtils.getInstance().isNotEmpty(providerCollection.getTotalPlasmaNum(), null)) {
                    cjl = providerCollection.getTotalPlasmaNum();
                }
            }

            if (AdscmBaseUtils.getInstance().isNotEmpty(lastdate, null)) {
                logger.info("`````````````````````间隔天数：" + (System.currentTimeMillis() - lastdate.getTime()) + " ，采浆量：" + cjl);
                if (((System.currentTimeMillis() - lastdate.getTime()) / (dayTime)) < 14 && cjl >= 150) {//如果采浆量小于150，则证明之前采浆过程出现了异常，后面可以继续登记采 yyy
                    throw new AdscmSystemException("间隔小于14天，不能登记！");
                }
            }

            bloodUser.setId(providerInfo.getCardId());
            bloodUser.setName(providerInfo.getName());
            bloodUser.setBirthday(providerInfo.getBirthday());
            bloodUser.setAddress(providerInfo.getAddress());
            bloodUser.setIdNumber(providerInfo.getIdNo());
            bloodUser.setAge(providerInfo.getAge());
            bloodUser.setNationality(AdscmBaseUtils.getInstance().getNation(providerInfo.getNation()));
            bloodUser.setValidPeriod(providerInfo.getIdCardValidDate());
            byte[] bytes = uploadService.downloadImageReturnBytes(providerInfo.getPhoto());
            bloodUser.setPhoto(bytes);
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getPhone(), null)) {
                bloodUser.setPhone(providerInfo.getPhone());
            }
            bloodUser.setCreateDate(providerInfo.getCreateDate());
            bloodUser.setType("合格");
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getSex(), null)) {
                JyCode jyCode = new JyCode();
                jyCode.setType(7);
                jyCode.setCode(providerInfo.getSex());
                jyCode = jyCodeMapper.selectOne(jyCode);
                if (AdscmBaseUtils.getInstance().isNotEmpty(jyCode, null)) {
                    bloodUser.setSex(jyCode.getName());
                } else {
                    bloodUser.setSex(providerInfo.getSex());
                }
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getBloodType(), null)) {
                JyCode jyCode = new JyCode();
                jyCode.setType(12);
                jyCode.setCode(providerInfo.getBloodType());
                jyCode = jyCodeMapper.selectOne(jyCode);
                if (AdscmBaseUtils.getInstance().isNotEmpty(jyCode, null)) {
                    bloodUser.setBloodType(jyCode.getName());
                } else {
                    bloodUser.setBloodType(providerInfo.getBloodType());
                }
            }
        }
        return bloodUser;
    }

    /**
     * 根据上传信息进行建档
     * @param bloodUser
     * @return
     * @throws AdscmSystemException
     */
    @Transactional
    @Override
    public BloodUser providerCreate(BloodUser bloodUser) throws AdscmSystemException {
        Boolean result = false;
        logger.info("开始建档流程");
        if (!AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getName(), null)) {
            throw new AdscmSystemException("姓名不能为空!");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getIdNumber(), null)) {
            throw new AdscmSystemException("身份证不能为空!");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getBirthday(), null)) {
            throw new AdscmSystemException("生日不能为空!");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getAge(), null)) {
            throw new AdscmSystemException("年龄不能为空!");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getSex(), null)) {
            throw new AdscmSystemException("性别不能为空!");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getAddress(), null)) {
            throw new AdscmSystemException("身份证地址不能为空!");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getIsThrouth(), null)) {
            throw new AdscmSystemException("是否通过验证不能为空!");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getNurse(), null)) {
            throw new AdscmSystemException("建档护士不能为空!");
        }
        //首先根据身份证到数据库查询是否已经建档
        Wrapper<ProviderInfo> providerInfoWrapper = new EntityWrapper<>();
        providerInfoWrapper.eq("idNo", bloodUser.getIdNumber());
        List<ProviderInfo> providerInfos = providerInfoMapper.selectList(providerInfoWrapper);
        if (providerInfos != null && providerInfos.size() > 0) {
            logger.info("建档流程:" + bloodUser.getIdNumber() + "证件号已经存在，无法建档 返回信息");
            ProviderInfo providerInfo = providerInfos.get(0);
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getPhoto(), null)) {
                byte[] bytes = uploadService.downloadImageReturnBytes(providerInfo.getPhoto());
                if (AdscmBaseUtils.getInstance().isNotEmpty(bytes, null)) {
                    bloodUser.setPhoto(bytes);
                }
            }
            bloodUser.setId(providerInfo.getCardId());
            return bloodUser;
        }
        logger.info("建档开始组装数据");
        ProviderInfo providerInfo = new ProviderInfo();
        providerInfo.setName(bloodUser.getName());
        providerInfo.setIdNo(bloodUser.getIdNumber());
        providerInfo.setBirthday(bloodUser.getBirthday());
        providerInfo.setAge(bloodUser.getAge());
        providerInfo.setIdNoAddress(bloodUser.getAddress());
        providerInfo.setAddress(bloodUser.getAddress());
        providerInfo.setIdCardValidDate(bloodUser.getRefuseDate());//身份证到期时间
        providerInfo.setCreateDate(new Date());
        providerInfo.setProvideAge(0);
        providerInfo.setCreateFileStartTime(new Date());
        providerInfo.setProviderState(0);//浆员状态正常
        providerInfo.setNation(AdscmBaseUtils.getInstance().getNationNO(bloodUser.getNationality()));//设置民族
        if (AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getPhoto(), null)) {
            String imagePath = uploadService.uploadImageByBytes(bloodUser.getPhoto());
            providerInfo.setPhoto(imagePath);
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getSex(), null)) {
            if ("男".equals(bloodUser.getSex())) {
                providerInfo.setSex("1");
            }
            if ("女".equals(bloodUser.getSex())) {
                providerInfo.setSex("2");
            }

        }
        providerInfo.setCreateNurse(bloodUser.getNurseId());
        providerInfo.setSftg(1);
        result = providerInfoService.insertProviderInfo(providerInfo, null);
        bloodUser.setId(providerInfo.getCardId());
        return bloodUser;
    }

    @Transactional
    @Override
    public RegisterData providerRegister(RegisterReqData registerReqData) throws AdscmSystemException {
        boolean result = false;
        boolean needPxp = false;//拍胸片
        String needPxpMsg = "";
        boolean needCxy = false;//采小样
        Date lastDate = null;//上一次采浆时间
        boolean isgd = true;//是否是固定浆员
        boolean isyq = false;//是否逾期
        boolean needXqdy = false;//血清电泳
        String code = registerReqData.getCode();
        RegisterData regdata = new RegisterData();
        if (!AdscmBaseUtils.getInstance().isNotEmpty(code, null)) {
            throw new AdscmSystemException("卡号不能为空！");
        }
        //根据这个卡号查询浆员的基本信息
        Wrapper<ProviderInfo> providerInfoWrapper = new EntityWrapper<>();
        providerInfoWrapper.eq("cardId", code);
        List<ProviderInfo> providerInfos = providerInfoMapper.selectList(providerInfoWrapper);
        if (providerInfos != null && providerInfos.size() <= 0) {
            throw new AdscmSystemException("没有找到与卡号【" + code + "】对应的供浆者信息");
        }
        ProviderInfo providerInfo = providerInfos.get(0);
        //查询上一次采浆时间

        Wrapper<ProviderCollection> providerCollectionWrapper = new EntityWrapper<>();
        providerCollectionWrapper.eq("providerNo", providerInfo.getId());
        providerCollectionWrapper.orderBy("createTime", false);
        providerCollectionWrapper.last("LIMIT 1");
        List<ProviderCollection> providerCollections = providerCollectionMapper.selectList(providerCollectionWrapper);
        if (providerCollections != null && providerCollections.size() > 0) {
            ProviderCollection providerCollection = providerCollections.get(0);
            lastDate = providerCollection.getCollectionDate();//获取到上一次采浆日期
            logger.info("浆员【" + code + " ：" + providerInfo.getName() + "】上次采浆日期为：" + lastDate);
        }
        //获取胸片信息
        Wrapper<ProviderXp> providerXpWrapper = new EntityWrapper<>();
        providerXpWrapper.eq("providerNo", providerInfo.getId());
        providerXpWrapper.orderBy("createDate", false);
        providerXpWrapper.last("LIMIT 1");
        List<ProviderXp> providerXps = providerXpMapper.selectList(providerXpWrapper);
        if (providerXps != null && providerXps.size() > 0) {
            ProviderXp providerXp = providerXps.get(0);
            Date validDate = providerXp.getValidDate();//胸片有效日期
            if (!AdscmBaseUtils.getInstance().isNotEmpty(validDate, null)) {
                needPxp = true;
                needPxpMsg = "【"+providerInfo.getName()+"】没有历史大体检记录，需要拍胸片！！";
            } else {

                //如果胸片有效期小于30天提示拍胸片
                List<String> betweenDate = AdscmDateUtils.getBetweenDate(new Date(), validDate);
                if (betweenDate.size() <= 30) {
                    needPxp = true;
                    String date = "";
                    if(providerXp.getCreateDate() != null){
                        date = AdscmDateUtils.getNowOnlyDateFomat1(providerXp.getCreateDate());
                    }
                    needPxpMsg = "【"+providerInfo.getName()+"】上次大体检的时间为【"+date+"】，需要尽快重新拍胸片了！！";
                }
            }
        }else{
            needPxp = true;
            needPxpMsg = "【"+providerInfo.getName()+"】没有历史大体检记录，需要拍胸片！！";
        }
        //查询缓存
        ProviderData providerData = providerDataMapper.selectById(Long.valueOf(providerInfo.getId()));
        if (AdscmBaseUtils.getInstance().isNotEmpty(providerData, null)) {

            regdata.setCode(code);//设置卡号
            regdata.setName(providerData.getName());
            regdata.setRegCode(providerData.getRegisterNo());
            regdata.setIdx(providerData.getRegisterIdx());//登记序号
            regdata.setRegTime(providerData.getRegisterTime());

            Calendar d = Calendar.getInstance();
            d.setTime(regdata.getRegTime());
            d.add(Calendar.DAY_OF_YEAR, 14);
            regdata.setNextTime(d.getTime());//下次献浆时间

            regdata.setExist(true);

            regdata.setNeedCxy(providerData.isNeedAssay());//是否需要化检
            regdata.setNeedPxp(needPxp);

            if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getPhone(), null)) {
                regdata.setPhone(providerInfo.getPhone());
            }
            //后续还有五部链接  链接护士  不良反应  链接任务之类的消息返回


        } else {
            synchronized (this) {
                //查询不到缓存,创建登记缓存

                providerData = new ProviderData();
                providerData.setProviderId(providerInfo.getId());
                providerData.setProviderNo(providerInfo.getCardId());
                providerData.setIdNo(providerInfo.getIdNo());
                providerData.setName(providerInfo.getName());
                providerData.setNeedXp(needPxp);
                providerData.setNeedXpMsg(needPxpMsg);
                //获取登记号与登记序号
                providerData = providerQueue.providerRegister(providerData);

                if ("1".equals(providerInfo.getSex())) {
                    providerData.setSex("男");
                }
                if ("2".equals(providerInfo.getSex())) {
                    providerData.setSex("女");
                }
                //将浆员人脸识别源文件夹中的照片改为当前登记照片
                try {
                    if ("1".equals(registerReqData.getRzfs())){//如果是人脸认证的话
                        String soursePath = this.sourcePath + providerData.getProviderNo() + ".jpg";
                        AdscmBaseUtils.getInstance().writeFileToDisk(registerReqData.getPhoto(),soursePath);
                        soursePath = this.sourcePath + providerData.getIdNo() + ".jpg";
                        AdscmBaseUtils.getInstance().writeFileToDisk(registerReqData.getPhoto(),soursePath);
                    }
                }catch (Exception e){
                    logger.error("写入本次登记照片到本地异常：" + e.getMessage());
                }

                if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getPhoto(), null)) {
                    byte[] bytes = uploadService.downloadImageReturnBytes(providerInfo.getPhoto());
                    if (AdscmBaseUtils.getInstance().isNotEmpty(bytes, null)) {
                        bytes = AdscmBaseUtils.getInstance().buildIcon(bytes, 240, 240);
//                          providerData.setPhoto(bytes);
                    } else {
                        bytes = AdscmBaseUtils.getInstance().buildIcon(registerReqData.getPhoto(), 240, 240);
                    }
                    providerData.setPhoto(bytes);
                }
                providerData.setRegisterTime(new Date());
                //创建登记记录
                ProviderReg providerReg = new ProviderReg();
                providerReg.setRegisterNo(providerData.getRegisterNo());
                providerReg.setRegisterIdx(providerData.getRegisterIdx());
                providerReg.setProviderNo(providerInfo.getId().toString());
                providerReg.setIdNo(providerInfo.getIdNo());
                providerReg.setRegTime(new Date());
                //判断是否要采样,先查询上一次小样记录
                providerData.setNeedAssay(false);
                isgd = true;
                Wrapper<PlasmaSamples> plasmaSamplesWrapper = new EntityWrapper<>();
                plasmaSamplesWrapper.eq("providerNo", providerInfo.getId());
                plasmaSamplesWrapper.orderBy("recodeTime", false);
                plasmaSamplesWrapper.last("LIMIT 1");
                List<PlasmaSamples> plasmaSamples = plasmaSamplesMapper.selectList(plasmaSamplesWrapper);
                if (lastDate != null) {
                    long days = (System.currentTimeMillis() - lastDate.getTime()) / (dayTime);
                    //上一次献浆大于180天
                    if (days >= 180) {
                        //判断小样是否存在
                        if (plasmaSamples != null && plasmaSamples.size() > 0) {
                            PlasmaSamples plasmaSample = plasmaSamples.get(0);

                            if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getRecodeTime(), null)) {
                                Date recodeTIme = plasmaSample.getRecodeTime();
                                //180天之类采过小样
                                if ((new Date().getTime() - recodeTIme.getTime()) / (dayTime) < 180) {
                                    //如果小于180天，且化检结果合格那么就可以不用化检了，否则就需要重新化检
                                    if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getInspectionResult(), null)) {
                                        if ("0".equals(plasmaSample.getInspectionResult())) {
                                            needCxy = false;
                                            providerData.setNeedAssay(false);
                                            isgd = true;
                                            logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "上次化检合格不用采样");
                                        } else {
                                            //上次采样不合格
                                            providerData.setNeedAssay(true);
                                            isgd = false;
                                            needCxy = true;
                                            logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "上次采样不合格，需要采小样化检");
                                        }
                                    } else {
                                        //没有化检结果 结果需要化检
                                        providerData.setNeedAssay(true);
                                        isgd = false;
                                        needCxy = true;
                                        logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "没有化检结果 需要采小样化检");
                                    }

                                } else {
                                    //小样大于了180天需要化检
                                    providerData.setNeedAssay(true);
                                    isgd = false;
                                    needCxy = true;
                                    logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "小样大于了180天需要采小样化检");
                                }
                            } else {
                                //化检无记录时间，需要化检
                                providerData.setNeedAssay(true);
                                isgd = false;
                                needCxy = true;
                                logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "化检无记录时间，需要采小样化检");
                            }

                        }else{
                            //采浆间隔大于了半年，并且半年内也没有化检记录
                            providerData.setNeedAssay(true);
                            isgd = false;
                            needCxy = true;
                            logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "半年内无献浆记录， 且无化检记录，需要采小样化检");
                        }

                    }else {
                        isgd = true;
                        providerData.setNeedAssay(false);
                        needCxy = false;
                        logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "固定浆员，无需采小样");
                    }
                    if (days > 20) {
                        isyq = true;
                        logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "逾期");
                    }

                } else {
                    //上次未采浆,首先看是否有小样记录
                    if (plasmaSamples != null && plasmaSamples.size() > 0) {
                        PlasmaSamples plasmaSample = plasmaSamples.get(0);
                        if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getRecodeTime(), null)) {
                            if ((new Date().getTime() - plasmaSample.getRecodeTime().getTime()) / (dayTime) < 180) {

                                if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getInspectionResult(), null)) {
                                    if ("0".equals(plasmaSample.getInspectionResult())) {
                                        //上次采小样结果合格，且在180天之内
                                        needCxy = false;
                                        providerData.setNeedAssay(false);
                                        isgd = true;
                                        logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "*上次采小样结果合格，且在180天之内");
                                    } else {
                                        //上次采小样结果不合格
                                        providerData.setNeedAssay(true);
                                        isgd = false;
                                        needCxy = true;
                                        logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "*上次采小样结果不合格");
                                    }

                                } else {
                                    //上次采小样结果为空
                                    providerData.setNeedAssay(true);
                                    isgd = false;
                                    needCxy = true;
                                    logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "*上次采小样结果为空");
                                }


                            } else {
                                //上次采小样时间已经超过180天需要采小样
                                providerData.setNeedAssay(true);
                                isgd = false;
                                needCxy = true;
                                logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "*上次采小样时间已经超过180天需要采小样");
                            }
                        } else {
                            //上次采浆时间没有，需采小样
                            providerData.setNeedAssay(true);
                            isgd = false;
                            needCxy = true;
                            logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "*上次采浆时间没有，需采小样");
                        }

                    } else {
                        //无小样，需要采小样
                        providerData.setNeedAssay(true);
                        isgd = false;
                        needCxy = true;
                        logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "*无小样，需要采小样");
                    }


                }

                providerReg.setNeedAssay(needCxy);
                //查询血清电泳清单，看是否需要做血清电泳
                Wrapper<ProviderXqdyqd> providerXqdyqdWrapper = new EntityWrapper<>();
                providerXqdyqdWrapper.eq("providerNo", providerInfo.getId());
                providerXqdyqdWrapper.orderBy("xqDate", false);
                providerXqdyqdWrapper.last("limit 1");
                List<ProviderXqdyqd> providerXqdyqds = providerXqdyqdMapper.selectList(providerXqdyqdWrapper);
                if (providerXqdyqds != null && providerXqdyqds.size() > 0) {
                    ProviderXqdyqd providerXqdyqd = providerXqdyqds.get(0);
                    if (AdscmBaseUtils.getInstance().isNotEmpty(providerXqdyqd.getXqDate(), null)) {
                        if ((new Date().getTime() - providerXqdyqd.getXqDate().getTime()) / (dayTime) < (365 - 20)) {
                            //血清电泳已经过期
                            needXqdy = true;
                            logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "血清电泳已经过期");
                        }

                    } else {
                        //血清电泳时间为空，需要血清电泳
                        needXqdy = true;
                        logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "血清电泳时间为空，需要血清电泳");
                    }
                } else {
                    //没有血清电泳，需要血清电泳
                    needXqdy = true;
                    logger.info(providerInfo.getId() + ":" + providerInfo.getName() + "没有血清电泳，需要血清电泳");
                }
                providerData.setNeedXqdy(needXqdy);
                providerReg.setNeedXqdy(needXqdy);//设置血清电泳
                providerReg.setThresholdValue(Float.valueOf(registerReqData.getPersonNum()));//设置识别阈值
                providerReg.setRegNurse(registerReqData.getWorker());//设置登记护士
                //1人脸识别2指纹识别3人工识别
                providerReg.setRzfs(registerReqData.getRzfs());
                providerReg.setCreateTime(new Date());
                byte[] regPhoto = registerReqData.getPhoto();
                String regPhotoPath = uploadService.uploadImageByBytes(regPhoto);
                providerReg.setRegPhoto(regPhotoPath);
                providerReg.setIfGdjy(isgd);
                providerReg.setYq(isyq);
                //同步
                providerReg.setModifyTime(new Date());
                providerReg.setSynDate(AdscmDateUtils.getFormateDate(new Date()));
                providerRegMapper.insert(providerReg);
                //生成待体检信息
                //先根据登记号查询一遍是否已经存在了体检信息;
                Wrapper<BodyCheck> bodyCheckWrapper = new EntityWrapper<>();
                bodyCheckWrapper.eq("registerNo", providerReg.getRegisterNo());
                bodyCheckWrapper.eq("providerNo", providerInfo.getId());
                List<BodyCheck> bodyChecks = bodyCheckMapper.selectList(bodyCheckWrapper);
                //没得体检信息需要创建体检信息
                if (!(bodyChecks != null && bodyChecks.size() > 0)) {
                    BodyCheck bodyCheck = new BodyCheck();
                    bodyCheck.setProviderNo(providerInfo.getId().toString());
                    bodyCheck.setRegisterNo(providerReg.getRegisterNo());
                    bodyCheck.setRecodeCreateTime(AdscmDateUtils.getDateFomat(new Date()));
                    bodyCheck.setRegisterOrder(providerData.getRegisterIdx());
                    //获取上一次体检信息
                    Wrapper<BodyCheck> getLastBodyCheckWrapper = new EntityWrapper<>();
                    getLastBodyCheckWrapper.eq("providerNo", providerInfo.getId());
                    getLastBodyCheckWrapper.orderBy("recodeCreateTime", false);
                    getLastBodyCheckWrapper.last("limit 1");
                    List<BodyCheck> lastBodyChecks = bodyCheckMapper.selectList(getLastBodyCheckWrapper);
                    if (lastBodyChecks != null && lastBodyChecks.size() > 0) {
                        BodyCheck lastbodyCheck = lastBodyChecks.get(0);
                        bodyCheck.setWeight(lastbodyCheck.getWeight());//上次体重
                        bodyCheck.setAnimalHeat(lastbodyCheck.getAnimalHeat());//上次的体温
                        bodyCheck.setPulse(lastbodyCheck.getPulse());//上次脉搏
                        bodyCheck.setHighBlood(lastbodyCheck.getHighBlood());//上次高压
                        bodyCheck.setLowBlood(lastbodyCheck.getLowBlood());//上次低压
                    }
                    bodyCheck.setChest(1);
                    bodyCheck.setAbdomen(1);
                    bodyCheck.setSkin(1);
                    bodyCheck.setFacial(1);
                    bodyCheck.setLimbs(1);
                    bodyCheck.setHealthSingle(0);
                    bodyCheck.setRecodeStatus(0);
                    bodyCheck.setMODIFY_TIME(AdscmDateUtils.getDateFomat(new Date()));
                    bodyCheck.setSYNDATE(AdscmDateUtils.getDateFormat(new Date()));
                    bodyCheckMapper.insert(bodyCheck);
                }
                //费用发放生产基础费用发放表
                //查询是否存在费用发放的记录
                Wrapper<ProviderCost> providerCostWrapper = new EntityWrapper<>();
                providerCostWrapper.eq("providerNo", providerInfo.getId());
                providerCostWrapper.eq("registerNo", providerReg.getRegisterNo());
                List<ProviderCost> providerCosts = providerCostMapper.selectList(providerCostWrapper);
                //没得费用记录
                if (!(providerCosts != null && providerCosts.size() > 0)) {
                    //根据浆员的地址计算费用
                    //查询出所有地址信息
                    int allowance = 0;
                    List<ProviderAddressAllowance> providerAddressAllowances = providerAddressAllowanceMapper.selectList(null);
                    String address = providerInfo.getAddress();
                    if (!AdscmBaseUtils.getInstance().isNotEmpty(address, null)) {
                        allowance = 0;
                    } else {
                        ProviderAddressAllowance addr = null;
                        for (ProviderAddressAllowance providerAddressAllowance : providerAddressAllowances) {
                            if (address.indexOf(providerAddressAllowance.getAddress()) >= 0) {
                                if (addr == null) {
                                    addr = providerAddressAllowance;
                                } else if (providerAddressAllowance.getAddress().length() > addr.getAddress().length()) {
                                    addr = providerAddressAllowance;
                                }
                            }
                        }
                        if (addr == null) {
                            allowance = 0;
                        } else {
                            if (null == addr.getAllowance()) {
                                allowance = 0;
                            } else {
                                allowance = addr.getAllowance();
                            }
                        }
                    }
                    ProviderCost providerCost = new ProviderCost();
                    providerCost.setProviderNo(providerInfo.getId().toString());
                    providerCost.setRegisterNo(providerReg.getRegisterNo());
                    providerCost.setIdNo(providerInfo.getIdNo());
                    providerCost.setCreateTime(new Date());
                    //添加频次补贴
                    Wrapper<ProviderCollection> getCollectionTimes=new EntityWrapper<>();
                    getCollectionTimes.eq("providerNo",providerInfo.getId());
                    getCollectionTimes.eq("isDeal","1");
                    //2019-
                    getCollectionTimes.ge("collectionDate","2019-02-01 00:00:00");
                    getCollectionTimes.le("collectionDate","2019-12-31 00:00:00");
                    Integer times = providerCollectionMapper.selectCount(getCollectionTimes);
                    times=times+1;
                    //根据次数查询补贴
                    Wrapper<ProviderTimesAllowance> providerTimesAllowanceWrapper =new EntityWrapper<>();
                    providerTimesAllowanceWrapper.eq("times",times);
                    List<ProviderTimesAllowance> providerTimesAllowances = providerTimesAllowanceMapper.selectList(providerTimesAllowanceWrapper);
                    int  timesAllowance=0;
                    if (providerTimesAllowances!=null&&providerAddressAllowances.size()>0 ){
                        timesAllowance=providerAddressAllowances.get(0).getAllowance();
                    }
                    providerCost.setTimesAllowance( Float.valueOf(timesAllowance+"") );
                    providerCost.setCollectionTimes(times);
                    providerCostMapper.insert(providerCost);
                }
                providerData.setCurrentStatus(1);
                providerDataMapper.updateById(providerData);//更新缓存
                MachineMgr.getInstance().sendMsgToAllotCtxs(BeanSupport.loadToAllotMsg(providerData, null));

                regdata.setCode(code);//设置卡号
                regdata.setName(providerData.getName());
                regdata.setRegCode(providerData.getRegisterNo());
                regdata.setIdx(providerData.getRegisterIdx());//登记序号
                regdata.setRegTime(providerData.getRegisterTime());

                Calendar d = Calendar.getInstance();
                d.setTime(regdata.getRegTime());
                d.add(Calendar.DAY_OF_YEAR, 14);
                regdata.setNextTime(d.getTime());//下次献浆时间
                regdata.setExist(true);
                regdata.setNeedCxy(providerData.isNeedAssay());//是否需要化检
                regdata.setNeedPxp(needPxp);
                if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getPhone(), null)) {
                    regdata.setPhone(providerInfo.getPhone());
                }

                //后续还有五部链接  链接护士  不良反应  链接任务之类的消息返回
            }//同步结束
        }//没查询到缓存结束


        return regdata;
    }

    /**
     * 保存建档照片
     *
     * @param bloodUser
     * @return
     * @throws AdscmSystemException
     */
    @Transactional
    @Override
    public boolean saveProviderCreatePhoto(BloodUser bloodUser) throws AdscmSystemException {
        boolean result = false;
        Wrapper<ProviderInfo> providerInfoWrapper = new EntityWrapper<>();
        providerInfoWrapper.eq("cardId", bloodUser.getId());
        List<ProviderInfo> providerInfos = providerInfoMapper.selectList(providerInfoWrapper);
        if (providerInfos != null && providerInfos.size() > 0) {
            ProviderInfo providerInfo = providerInfos.get(0);
            String photoPath = uploadService.uploadImageByBytes(bloodUser.getPhoto());
            providerInfo.setPhoto(photoPath);
            providerInfo.setModifyTime(new Date());
            Integer integer = providerInfoMapper.updateById(providerInfo);
            if (integer == 1) {
                result = true;
                //修改缓存中的建档照片
                ProviderData providerData = new ProviderData();
                providerData.setIdNo(providerInfo.getIdNo());
                providerData = providerQueue.selectProviderData(providerData);
                if (providerData.getProviderId() > 0){
                    //修改缓存
                    byte[] bytes = AdscmBaseUtils.getInstance().buildIcon(bloodUser.getPhoto(), 240, 240);
                    providerData.setPhoto(bytes);
                    providerQueue.updateProviderData(providerData);

                    try{
                        //删除文件系统中用于人脸比对的建档照片，下次人脸比对，就会下载新的照片进行比对
                        String soursePath = this.sourcePath + providerData.getProviderNo() + ".jpg";
                        AdscmBaseUtils.getInstance().delFile(soursePath);
                        soursePath = this.sourcePath + providerData.getIdNo() + ".jpg";
                        AdscmBaseUtils.getInstance().delFile(soursePath);
                    }catch (Exception e){}
                }

            }
        } else {
            throw new AdscmSystemException("未查找该浆员信息！");
        }

        return result;
    }

    /**
     * 保存指纹信息
     * @param fingerprints
     * @param cardId
     * @return
     * @throws AdscmSystemException
     */
    @Transactional
    @Override
    public boolean saveProviderCreateZw(List<Fingerprint> fingerprints, String cardId) throws AdscmSystemException {
        if (AdscmBaseUtils.getInstance().isNotEmpty(cardId, null)) {
            //查询这个人的基本信息
            Wrapper<ProviderInfo> providerInfoWrapper = new EntityWrapper<>();
            providerInfoWrapper.eq("cardId", cardId);
            List<ProviderInfo> providerInfos = providerInfoMapper.selectList(providerInfoWrapper);
            if (providerInfos != null && providerInfos.size() > 0) {
                ProviderInfo providerInfo = providerInfos.get(0);
                for (Fingerprint fingerprint : fingerprints) {
                    ProviderZw providerZw = new ProviderZw();
                    providerZw.setProviderNo(providerInfo.getId());
                    providerZw.setZw(fingerprint.getZw());
                    providerZw.setCode(fingerprint.getCode());
                    //先查询一下是否存在这个手指的数据
                    Wrapper<ProviderZw> providerZwWrapper = new EntityWrapper<>();
                    providerZwWrapper.eq("providerNo", providerZw.getProviderNo());
                    providerZwWrapper.eq("code", providerZw.getCode());

                    List<ProviderZw> providerZws = providerZwMapper.selectList(providerZwWrapper);
                    if (providerZws != null && providerZws.size() > 0) {
//                        providerZwMapper.updateById(providerZw);
                        providerZwMapper.update(providerZw,providerZwWrapper);
                    } else {
                        providerZwMapper.insert(providerZw);
                    }

                }
            } else {
                throw new AdscmSystemException("没有查到这个浆员");
            }


        } else {
            throw new AdscmSystemException("没有卡号信息");
        }

        return false;
    }

    /**
     * 获取指纹信息
     * @param cardId
     * @return
     * @throws AdscmSystemException
     */
    @Override
    public List<Fingerprint> getProviderCreateZw(String cardId) throws AdscmSystemException {

        List<Fingerprint> fingerprints = new ArrayList<>();
        //判断卡号是否为空
        if (AdscmBaseUtils.getInstance().isNotEmpty(cardId, null)) {

            Wrapper<ProviderInfo> providerInfoWrapper = new EntityWrapper<>();
            providerInfoWrapper.eq("cardId", cardId);
            List<ProviderInfo> providerInfos = providerInfoMapper.selectList(providerInfoWrapper);
            if (providerInfos != null && providerInfos.size() > 0) {
                ProviderInfo providerInfo = providerInfos.get(0);
                //查询指纹信息
                Wrapper<ProviderZw> providerZwWrapper = new EntityWrapper<>();
                providerZwWrapper.eq("providerNo", providerInfo.getId());
                List<ProviderZw> providerZws = providerZwMapper.selectList(providerZwWrapper);
                for (ProviderZw providerZw : providerZws) {
                    Fingerprint fingerprint = new Fingerprint();
                    fingerprint.setCode(providerZw.getCode());
                    fingerprint.setZw(providerZw.getZw());
                    fingerprints.add(fingerprint);
                }
            } else {
                throw new AdscmSystemException("没有浆员信息");
            }

        } else {
            throw new AdscmSystemException("卡号信息为空");
        }
        return fingerprints;
    }

    /**
     * 自动分配
     * @param code
     * @param nurseid
     * @return
     * @throws AdscmSystemException
     */
    @Override
    public AllotData autoAllotByProvider(String code, String nurseid) throws AdscmSystemException {
        if (!AdscmBaseUtils.getInstance().isNotEmpty(code,null)){
            throw  new AdscmSystemException("浆员卡号信息不存在");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(nurseid,null)){
            throw  new AdscmSystemException("护士信息不存在");
        }
        if (code.startsWith("R")){
            throw  new AdscmSystemException("新浆员不能建档");
        }
        //先从缓存中读取浆员信息
        ProviderData providerData = providerQueue.getByProviderNo(code);
        if (!AdscmBaseUtils.getInstance().isNotEmpty(providerData,null)){
            throw  new AdscmSystemException("没有登记");//没在缓存中查找浆员信息
        }
        ProviderInfo providerInfo = providerInfoMapper.selectById(providerData.getProviderId());
        if (!AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
            throw  new AdscmSystemException("没在查找浆员信息");
        }



        //缓存 中查看是否要采小样
        if (providerData.isNeedAssay()){
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerData.isAssayIsPass(),null)){
                if (!providerData.isAssayIsPass()){
                    throw  new AdscmSystemException("浆员化检未通过");
                }
            }else {
                throw  new AdscmSystemException("浆员未化检");
            }
        }
        //缓存中是否要需要拍胸片
        if (providerData.isNeedXp()){
            Wrapper<ProviderXp> providerXpWrapper =new EntityWrapper<>();
            providerXpWrapper.eq("providerNo",providerInfo.getId());
            providerXpWrapper.orderBy("validDate",false);
            List<ProviderXp> providerXps = providerXpMapper.selectList(providerXpWrapper);
            if (providerXps!=null&&providerXps.size()>0){
                ProviderXp providerXp = providerXps.get(0);
                //胸片记录已经过了有效期提示拍胸片
                if (new Date().getTime()>providerXp.getValidDate().getTime()){
                    throw   new AdscmSystemException("胸片已过期,请从新拍摄胸片");
                }
                //胸片不合格
                if ("0".equals(providerXp.getResult())){
                    throw   new AdscmSystemException("胸片不合格,不能分配");
                }
            }else {
                throw new AdscmSystemException("浆员还没上传胸片信息");
            }
        }
        //缓存中查看体检是否合格，不合格不分配
        if (AdscmBaseUtils.getInstance().isNotEmpty(providerData.isBodyIsPass(),null)){
            if (!providerData.isBodyIsPass()){
                throw new AdscmSystemException("体检结果不合格");
            }

        }else {
            throw new AdscmSystemException("还未体检");
        }
        AllotData allotData = MachineMgr.getInstance().autoAllotByProvider(providerData,providerInfo);
        if (AdscmBaseUtils.getInstance().isNotEmpty(allotData,null)){
            providerData.setMachineCode(allotData.getMachineCode());
            //生成分配的分配记录
            logger.info("生成分配记录");
            //先查询是否有分配记录,如果有就更新，没有就生成
            Wrapper<ProviderAllot> providerAllotWrapper =new EntityWrapper<>();
            providerAllotWrapper.eq("providerNo",providerInfo.getId().toString());
            providerAllotWrapper.eq("registerNo",providerData.getRegisterNo());
            List<ProviderAllot> providerAllots = providerAllotMapper.selectList(providerAllotWrapper);
            if (providerAllots!=null&&providerAllots.size()>0){
                ProviderAllot providerAllot = providerAllots.get(0);
                providerAllot.setAllotDate(new Date());
                providerAllot.setMachineNo(allotData.getMachineNo());
                providerAllot.setAllotType("1");//自动分配
                providerAllot.setCreator(nurseid);
                providerAllotMapper.updateById(providerAllot);
            }else {
                ProviderAllot providerAllot = new ProviderAllot();
                providerAllot.setAllotDate(new Date());
                providerAllot.setMachineNo(allotData.getMachineNo());
                providerAllot.setRegisterNo(providerData.getRegisterNo());
                providerAllot.setProviderNo(providerInfo.getId().toString());
                providerAllot.setAllotType("1");//自动分配
                providerAllot.setCreator(nurseid);
                providerAllot.setModifyTime(new Date());
                providerAllot.setSynDate(AdscmDateUtils.getFormateDate(new Date()));
                providerAllotMapper.insert(providerAllot);
            }
            //根据缓存中信息判断是否需要添加血清电泳的记录
            if (providerData.isNeedXqdy()){
                //先查询是否已经添加了血清电泳
                if (!AdscmBaseUtils.getInstance().isNotEmpty(providerData.getXqdyId(),null)){
                    Wrapper<ProviderXqdyqd> providerXqdyqdWrapper =new EntityWrapper<>();
                    providerXqdyqdWrapper.eq("providerNo",providerInfo.getId());
                    providerXqdyqdWrapper.eq("registerNo",providerData.getRegisterNo());
                    List<ProviderXqdyqd> providerXqdyqds = providerXqdyqdMapper.selectList(providerXqdyqdWrapper);
                    if (providerXqdyqds!=null&& providerXqdyqds.size()>0){
                        //存在血清电泳
                        ProviderXqdyqd providerXqdyqd = providerXqdyqds.get(0);
                        Integer cidx = providerXqdyqd.getCidx();
                        String id = providerXqdyqd.getId();
                        DecimalFormat decimalFormat =new DecimalFormat("00");
                        String cidxStr = decimalFormat.format(cidx);
                        providerData.setXqdyId("302D" + id + "-" + cidxStr);
                    }else {

                        //没得血清电泳
                        //首先到血清电泳批号中获取目前倒序最大的一条
                        ProviderXqdyph providerXqdyph=new ProviderXqdyph();
                        String year = new SimpleDateFormat("yyyy").format(new Date());
                        Wrapper<ProviderXqdyph> providerXqdyphWrapper=new EntityWrapper<>();
                        providerXqdyphWrapper.orderBy("xqYear",false);
                        providerXqdyphWrapper.orderBy("xqPc",false);
                        providerXqdyphWrapper.last("limit 1");
                        List<ProviderXqdyph> providerXqdyphs = providerXqdyphMapper.selectList(providerXqdyphWrapper);
                        if (providerXqdyphs!=null&&providerXqdyphs.size()>0){
                            providerXqdyph = providerXqdyphs.get(0);
                            Integer xqYear = providerXqdyph.getXqYear();
                            if (year.equals(xqYear.toString())){
                                //是一年的血清电泳批号
                                int xqIdx=providerXqdyph.getXqIdx()+1;
                                if ( xqIdx> 99) {
                                    //在这条批号后面生成一条新的
                                    providerXqdyph.setXqIdx(1);
                                    providerXqdyph.setXqPc(providerXqdyph.getXqPc()+1);
                                    providerXqdyph.setId(String.valueOf(Integer.valueOf(providerXqdyph.getId())+1));
                                    providerXqdyphMapper.insert(providerXqdyph);
                                }else {
                                    //还在99内就把序号加一更新
                                    providerXqdyph.setXqIdx(providerXqdyph.getXqIdx()+1);
                                    providerXqdyphMapper.updateById(providerXqdyph);
                                }

                            }else {
                                //不是今年的血清电泳批号了  新建一条
                                providerXqdyph =new ProviderXqdyph();
                                providerXqdyph.setXqYear(Integer.valueOf(year));
                                providerXqdyph.setXqPc(1);
                                providerXqdyph.setXqIdx(1);
                                DecimalFormat decimalFormat =new DecimalFormat("000");
                                providerXqdyph.setId(year.substring(2)+decimalFormat.format(providerXqdyph.getXqPc()));
                                providerXqdyphMapper.insert(providerXqdyph);
                            }
                        }else{
                            //没有任何 新建
                            providerXqdyph =new ProviderXqdyph();
                            providerXqdyph.setXqYear(Integer.valueOf(year));
                            providerXqdyph.setXqPc(1);
                            providerXqdyph.setXqIdx(1);
                            DecimalFormat decimalFormat =new DecimalFormat("000");
                            providerXqdyph.setId(year.substring(2)+decimalFormat.format(providerXqdyph.getXqPc()));
                            providerXqdyphMapper.insert(providerXqdyph);
                        }
                        //新建一条血清电泳的清单
                        ProviderXqdyqd providerXqdyqd = new ProviderXqdyqd();
                        providerXqdyqd.setProviderNo(providerInfo.getId().toString());
                        providerXqdyqd.setRegisterNo(providerData.getRegisterNo());
                        providerXqdyqd.setXqDate(new Date());
                        providerXqdyqd.setCidx(providerXqdyph.getXqIdx());
                        providerXqdyqd.setId(providerXqdyph.getId());
                        providerXqdyqdMapper.insert(providerXqdyqd);
                        Integer cidx = providerXqdyqd.getCidx();
                        String id = providerXqdyqd.getId();
                        DecimalFormat decimalFormat =new DecimalFormat("00");
                        String cidxStr = decimalFormat.format(cidx);
                        providerData.setXqdyId("302D" + id + "-" + cidxStr);
                    }
                }
                allotData.setXqdyId(providerData.getXqdyId());
            }//-----结束血清电泳的添加
            //生成待处理采浆记录
            //查询一次是否已经添加了
            Wrapper<ProviderCollection> providerCollectionWrapper =new EntityWrapper<>();
            providerCollectionWrapper.eq("providerNo",providerInfo.getId());
            providerCollectionWrapper.eq("registerNo",providerData.getRegisterNo());
            List<ProviderCollection> providerCollections = providerCollectionMapper.selectList(providerCollectionWrapper);
            if (!(providerCollections!=null&&providerCollections.size()>0)){
                //没有采浆记录
                ProviderCollection providerCollection =new ProviderCollection();
                providerCollection.setIdNo(providerInfo.getIdNo());
                providerCollection.setRegisterNo(providerData.getRegisterNo());
                providerCollection.setProviderNo(providerInfo.getId().toString());
                providerCollection.setCreateTime(new Date());
                providerCollection.setCollectionDate(AdscmDateUtils.getFormateDate(new Date()));
                providerCollection.setMachineNo(allotData.getMachineNo());
                MachineData machine = MachineMgr.getInstance().getMachine(allotData.getMachineCode());
                providerCollection.setNurse(machine.getNurseCode());
                providerCollectionMapper.insert(providerCollection);
                logger.info("生成"+providerInfo.getName()+":"+providerInfo.getId()+"待采浆记录");
                providerData.setCollectId(providerCollection.getId());
            }

        }

        //发送消息给一体机
//        sendAllotMacInfo(allotData.getMachineCode());
        MachineData machine = MachineMgr.getInstance().getMachine(allotData.getMachineCode());
        MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(machine));
        providerData.setAllotTime(new Date());
        providerData.setCurrentStatus(6);//已经分配
        //修改缓存
        providerQueue.updateProviderData(providerData);
        //查询登记记录修改登记中的信息
        Wrapper<ProviderReg> providerRegWrapper=new EntityWrapper<>();
        providerRegWrapper.eq("providerNo",String.valueOf(providerInfo.getId()) );
        providerRegWrapper.eq("registerNo",providerData.getRegisterNo());
        List<ProviderReg> providerRegs = providerRegMapper.selectList(providerRegWrapper);
        if (providerRegs!=null&& providerRegs.size()>0){
            ProviderReg providerReg = providerRegs.get(0);
            providerReg.setMachineCode(allotData.getMachineNo());
            if (AdscmBaseUtils.getInstance().isNotEmpty(allotData.getXqdyId(),null)){
                providerReg.setXqdyId(allotData.getXqdyId());
            }
            providerRegMapper.updateById(providerReg);
        }


        //发送缓存消息给分配机
        MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(providerData,null));
        MachineMgr.getInstance().updateRedisMachineData(objectRedisTemplate,machine);

        return allotData;
    }

    /**
     * 手动分配
     * @param code
     * @param nurseid
     * @param mcode
     * @return
     * @throws AdscmSystemException
     */
    @Override
    public AllotData manualAllotByProvider(String code, String nurseid, String mcode) throws AdscmSystemException {
        if (!AdscmBaseUtils.getInstance().isNotEmpty(code,null)){
            throw  new AdscmSystemException("浆员卡号信息不存在");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(nurseid,null)){
            throw  new AdscmSystemException("护士信息不存在");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(mcode,null)){
            throw  new AdscmSystemException("设备编号无效！");
        }

        if (code.startsWith("R")){
            throw  new AdscmSystemException("新浆员不能分配");
        }
        //先从缓存中读取浆员信息
        ProviderData providerData = providerQueue.getByProviderNo(code);
        if (!AdscmBaseUtils.getInstance().isNotEmpty(providerData,null)){
            throw  new AdscmSystemException("没有登记");//没在缓存中查找浆员信息
        }
        ProviderInfo providerInfo = providerInfoMapper.selectById(providerData.getProviderId());
        if (!AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
            throw  new AdscmSystemException("没在查找浆员信息");
        }

        //缓存 中查看是否要采小样
        if (providerData.isNeedAssay()){
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerData.isAssayIsPass(),null)){
                if (!providerData.isAssayIsPass()){
                    throw  new AdscmSystemException("浆员化检未通过");
                }
            }else {
                throw  new AdscmSystemException("浆员未化检");
            }
        }
        //缓存中是否要需要拍胸片
        if (providerData.isNeedXp()){
            Wrapper<ProviderXp> providerXpWrapper =new EntityWrapper<>();
            providerXpWrapper.eq("providerNo",providerInfo.getId());
            providerXpWrapper.orderBy("validDate",false);
            List<ProviderXp> providerXps = providerXpMapper.selectList(providerXpWrapper);
            if (providerXps!=null&&providerXps.size()>0){
                ProviderXp providerXp = providerXps.get(0);
                //胸片记录已经过了有效期提示拍胸片
                if (new Date().getTime()>providerXp.getValidDate().getTime()){
                    throw   new AdscmSystemException("胸片已过期,请从新拍摄胸片");
                }
                //胸片不合格
                if ("0".equals(providerXp.getResult())){
                    throw   new AdscmSystemException("胸片不合格,不能分配");
                }
            }else {
                throw new AdscmSystemException("浆员还没上传胸片信息");
            }
        }
        //缓存中查看体检是否合格，不合格不分配
        if (AdscmBaseUtils.getInstance().isNotEmpty(providerData.isBodyIsPass(),null)){
            if (!providerData.isBodyIsPass()){
                throw new AdscmSystemException("体检结果不合格");
            }

        }else {
            throw new AdscmSystemException("还未体检");
        }
        AllotData allotData = MachineMgr.getInstance().manualAllotByProvider(providerData,providerInfo,mcode);
        if (AdscmBaseUtils.getInstance().isNotEmpty(allotData,null)){
            providerData.setMachineCode(allotData.getMachineCode());
            //生成分配的分配记录
            logger.info("生成分配记录");
            //先查询是否有分配记录,如果有就更新，没有就生成
            Wrapper<ProviderAllot> providerAllotWrapper =new EntityWrapper<>();
            providerAllotWrapper.eq("providerNo",providerInfo.getId().toString());
            providerAllotWrapper.eq("registerNo",providerData.getRegisterNo());
            List<ProviderAllot> providerAllots = providerAllotMapper.selectList(providerAllotWrapper);
            if (providerAllots!=null&&providerAllots.size()>0){
                ProviderAllot providerAllot = providerAllots.get(0);
                providerAllot.setAllotDate(new Date());
                providerAllot.setMachineNo(allotData.getMachineNo());
                providerAllot.setAllotType("2");//手动分配
                providerAllot.setCreator(nurseid);
                providerAllotMapper.updateById(providerAllot);
            }else {
                ProviderAllot providerAllot = new ProviderAllot();
                providerAllot.setAllotDate(new Date());
                providerAllot.setMachineNo(allotData.getMachineNo());
                providerAllot.setRegisterNo(providerData.getRegisterNo());
                providerAllot.setProviderNo(providerInfo.getId().toString());
                providerAllot.setAllotType("2");//手动分配
                providerAllot.setCreator(nurseid);
                providerAllot.setModifyTime(new Date());
                providerAllot.setSynDate(AdscmDateUtils.getFormateDate(new Date()));
                providerAllotMapper.insert(providerAllot);
            }
            //根据缓存中信息判断是否需要添加血清电泳的记录
            if (providerData.isNeedXqdy()){
                //先查询是否已经添加了血清电泳
                if (!AdscmBaseUtils.getInstance().isNotEmpty(providerData.getXqdyId(),null)){
                    Wrapper<ProviderXqdyqd> providerXqdyqdWrapper =new EntityWrapper<>();
                    providerXqdyqdWrapper.eq("providerNo",providerInfo.getId());
                    providerXqdyqdWrapper.eq("registerNo",providerData.getRegisterNo());
                    List<ProviderXqdyqd> providerXqdyqds = providerXqdyqdMapper.selectList(providerXqdyqdWrapper);
                    if (providerXqdyqds!=null&& providerXqdyqds.size()>0){
                        //存在血清电泳
                        ProviderXqdyqd providerXqdyqd = providerXqdyqds.get(0);
                        Integer cidx = providerXqdyqd.getCidx();
                        String id = providerXqdyqd.getId();
                        DecimalFormat decimalFormat =new DecimalFormat("00");
                        String cidxStr = decimalFormat.format(cidx);
                        providerData.setXqdyId("302D" + id + "-" + cidxStr);
                    }else {

                        //没得血清电泳
                        //首先到血清电泳批号中获取目前倒序最大的一条
                        ProviderXqdyph providerXqdyph=new ProviderXqdyph();
                        String year = new SimpleDateFormat("yyyy").format(new Date());
                        Wrapper<ProviderXqdyph> providerXqdyphWrapper=new EntityWrapper<>();
                        providerXqdyphWrapper.orderBy("xqYear",false);
                        providerXqdyphWrapper.orderBy("xqPc",false);
                        providerXqdyphWrapper.last("limit 1");
                        List<ProviderXqdyph> providerXqdyphs = providerXqdyphMapper.selectList(providerXqdyphWrapper);
                        if (providerXqdyphs!=null&&providerXqdyphs.size()>0){
                            providerXqdyph = providerXqdyphs.get(0);
                            Integer xqYear = providerXqdyph.getXqYear();
                            if (year.equals(xqYear.toString())){
                                //是一年的血清电泳批号
                                int xqIdx=providerXqdyph.getXqIdx()+1;
                                if ( xqIdx> 99) {
                                    //在这条批号后面生成一条新的
                                    providerXqdyph.setXqIdx(1);
                                    providerXqdyph.setXqPc(providerXqdyph.getXqPc()+1);
                                    providerXqdyph.setId(String.valueOf(Integer.valueOf(providerXqdyph.getId())+1));
                                    providerXqdyphMapper.insert(providerXqdyph);
                                }else {
                                    //还在99内就把序号加一更新
                                    providerXqdyph.setXqIdx(providerXqdyph.getXqIdx()+1);
                                    providerXqdyphMapper.updateById(providerXqdyph);
                                }

                            }else {
                                //不是今年的血清电泳批号了  新建一条
                                providerXqdyph =new ProviderXqdyph();
                                providerXqdyph.setXqYear(Integer.valueOf(year));
                                providerXqdyph.setXqPc(1);
                                providerXqdyph.setXqIdx(1);
                                DecimalFormat decimalFormat =new DecimalFormat("000");
                                providerXqdyph.setId(year.substring(2)+decimalFormat.format(providerXqdyph.getXqPc()));
                                providerXqdyphMapper.insert(providerXqdyph);
                            }
                        }else{
                            //没有任何 新建
                            providerXqdyph =new ProviderXqdyph();
                            providerXqdyph.setXqYear(Integer.valueOf(year));
                            providerXqdyph.setXqPc(1);
                            providerXqdyph.setXqIdx(1);
                            DecimalFormat decimalFormat =new DecimalFormat("000");
                            providerXqdyph.setId(year.substring(2)+decimalFormat.format(providerXqdyph.getXqPc()));
                            providerXqdyphMapper.insert(providerXqdyph);
                        }
                        //新建一条血清电泳的清单
                        ProviderXqdyqd providerXqdyqd = new ProviderXqdyqd();
                        providerXqdyqd.setProviderNo(providerInfo.getId().toString());
                        providerXqdyqd.setRegisterNo(providerData.getRegisterNo());
                        providerXqdyqd.setXqDate(new Date());
                        providerXqdyqd.setCidx(providerXqdyph.getXqIdx());
                        providerXqdyqd.setId(providerXqdyph.getId());
                        providerXqdyqdMapper.insert(providerXqdyqd);
                        Integer cidx = providerXqdyqd.getCidx();
                        String id = providerXqdyqd.getId();
                        DecimalFormat decimalFormat =new DecimalFormat("00");
                        String cidxStr = decimalFormat.format(cidx);
                        providerData.setXqdyId("302D" + id + "-" + cidxStr);
                    }
                }
                allotData.setXqdyId(providerData.getXqdyId());
            }//-----结束血清电泳的添加
            //生成待处理采浆记录
            //查询一次是否已经添加了
            Wrapper<ProviderCollection> providerCollectionWrapper =new EntityWrapper<>();
            providerCollectionWrapper.eq("providerNo",providerInfo.getId());
            providerCollectionWrapper.eq("registerNo",providerData.getRegisterNo());
            List<ProviderCollection> providerCollections = providerCollectionMapper.selectList(providerCollectionWrapper);
            if (!(providerCollections!=null&&providerCollections.size()>0)){
                //没有采浆记录
                ProviderCollection providerCollection =new ProviderCollection();
                providerCollection.setIdNo(providerInfo.getIdNo());
                providerCollection.setRegisterNo(providerData.getRegisterNo());
                providerCollection.setProviderNo(providerInfo.getId().toString());
                providerCollection.setCreateTime(new Date());
                providerCollection.setCollectionDate(AdscmDateUtils.getFormateDate(new Date()));
                providerCollection.setMachineNo(allotData.getMachineNo());
                MachineData machine = MachineMgr.getInstance().getMachine(allotData.getMachineCode());
                providerCollection.setNurse(machine.getNurseCode());
                providerCollectionMapper.insert(providerCollection);
                logger.info("生成"+providerInfo.getName()+":"+providerInfo.getId()+"待采浆记录");
                providerData.setCollectId(providerCollection.getId());
            }

        }
        //发送消息给一体机
//        sendAllotMacInfo(allotData.getMachineCode());
        MachineData machine = MachineMgr.getInstance().getMachine(allotData.getMachineCode());
        MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(machine));
        providerData.setAllotTime(new Date());
        providerData.setCurrentStatus(6);//已经分配
        //修改缓存
        providerQueue.updateProviderData(providerData);
        //查询登记记录修改登记中的信息
        Wrapper<ProviderReg> providerRegWrapper=new EntityWrapper<>();
        providerRegWrapper.eq("providerNo",String.valueOf(providerInfo.getId()) );
        providerRegWrapper.eq("registerNo",providerData.getRegisterNo());
        List<ProviderReg> providerRegs = providerRegMapper.selectList(providerRegWrapper);
        if (providerRegs!=null&& providerRegs.size()>0){
            ProviderReg providerReg = providerRegs.get(0);
            providerReg.setMachineCode(allotData.getMachineNo());
            if (AdscmBaseUtils.getInstance().isNotEmpty(allotData.getXqdyId(),null)){
                providerReg.setXqdyId(allotData.getXqdyId());
            }
            providerRegMapper.updateById(providerReg);
        }
        //发送缓存消息给分配机
        MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(providerData,null));
        MachineMgr.getInstance().updateRedisMachineData(objectRedisTemplate,machine);
        return allotData;
    }
    /**
     * 修改体检记录
     * @param bloodUser
     * @return
     * @throws AdscmSystemException
     */
    @Transactional
    @Override
    public BloodUser bodycheckMsg(BloodUser bloodUser) throws AdscmSystemException {

        ProviderData providerData = null;
        if (bloodUser != null && AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getId(),null)){
            providerData = providerQueue.getByProviderNo(bloodUser.getId());
            if(providerData == null){
                throw new AdscmSystemException("没有查询到该浆员当天的登记信息");
            }
        }else {
            throw new AdscmSystemException("参数异常");
        }

        Wrapper<BodyCheck> bodyCheckWrapper=new EntityWrapper<>();
        bodyCheckWrapper.eq("providerNo",providerData.getProviderId()).
                like("recodeCreateTime",AdscmDateUtils.getTodayAndTomorrow(new Date())[0]);
        List<BodyCheck> bodyCheckList = bodyCheckMapper.selectList(bodyCheckWrapper);
        BodyCheck bodyCheck=null;
        if (CollectionUtils.isEmpty(bodyCheckList)){
            throw new AdscmSystemException("没有查询到该浆员体检生成记录");
        }else {
            bodyCheck=bodyCheckList.get(0);
            if (AdscmBaseUtils.getInstance().isNotEmpty(bodyCheck.getBodyCheckNo(),null)){
                logger.info("已经体检过了...");
                return bloodUser;
            }
        }
//        Wrapper<ProviderXp> providerXpWrapper=new EntityWrapper<>();
//        providerXpWrapper.eq("providerNo",bodyCheck.getProviderNo()).orderBy("createDate",false);
//        providerXpWrapper.last("LIMIT 1");
//        List<ProviderXp> providerXps = providerXpMapper.selectList(providerXpWrapper); //查询最后一次拍摄胸片日期
//        if (AdscmBaseUtils.getInstance().isNotEmpty(providerXps,null)){
//            if (providerXps.size()>0){
//                List<String> betweenDate = AdscmDateUtils.getBetweenDate(new Date(),providerXps.get(0).getValidDate());
//                if (betweenDate.size()<=30) {
//
//                    bloodUser.setBodyCheckMsg("需要拍摄胸片");
//                }
//            }
//        }
        bodyCheck.setCreateNurse(bloodUser.getNurseId());
//        bodyCheck.setBodyCheckWorker(bloodUser.getNurseId());
        bodyCheck.setThreshold(bloodUser.getThreshold());
        bodyCheck.setAuthMethod(bloodUser.getRzfs());
//        if (!AdscmBaseUtils.getInstance().isNotEmpty(bodyCheck.getProviderNo(), null)) {
//            throw new AdscmSystemException("卡号不能为空");
//        }
//
//        if (AdscmBaseUtils.getInstance().isNotEmpty(bodyCheck.getCreateNurse(), null)) {
//            throw new AdscmSystemException("护士姓名不能为空");
//        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getPhoto(), null)) {
            String imagePath = uploadService.uploadImageByBytes(bloodUser.getPhoto());
            bodyCheck.setBodyCheckPhoto(imagePath);
        }
        Wrapper<BodyCheck> wrapper = new EntityWrapper<>();
        wrapper.like("recodeCreateTime", AdscmDateUtils.getTodayAndTomorrow(new Date())[0])
                .orderBy("bodyCheckOrder",false);
        wrapper.last("limit 1");
        List<BodyCheck> list = bodyCheckMapper.selectList(wrapper);
        int bodyCheckNo = 1;
        if (list.size() > 0) {
            Integer checkOrder = list.get(0).getBodyCheckOrder();
            if (checkOrder != null){
                bodyCheckNo = checkOrder + 1;//生成浆员序号
            }
        }
        NumberFormat numberFormat = new DecimalFormat("0000");
        String tjNo= AdscmDateUtils.getNowOnlyDateFomat2(new Date()) + numberFormat.format(bodyCheckNo);

        bodyCheck.setBodyStartTime(AdscmDateUtils.getDateFomat(new Date()));
        bodyCheck.setBodyCheckNo(tjNo);
        bodyCheck.setBodyCheckOrder(bodyCheckNo);
        bodyCheck.setRecodeStatus(0);
        bodyCheckMapper.updateById(bodyCheck);

        providerData.setBodyCheckId(bodyCheck.getBodyRecodeId());
        providerData.setBodyCheckCallTime(new Date());
        providerData.setBodyCheckNo(tjNo);
        providerData.setCurrentStatus(ProviderQueue.BODYCALL);
        providerDataMapper.updateById(providerData);
        MachineMgr.getInstance().sendMsgToAllotCtxs(BeanSupport.loadToAllotMsg(providerData, "body"));

        return bloodUser;
    }

    @Override
    public void doProcessProvider(String code, String cmd) throws AdscmSystemException {
        try {
            logger.info("处理操作【" + code + "：" + cmd + "】");
            ProviderData providerData = null;

            if (code != null && !"".equals(code)) {

                providerData = providerQueue.getByProviderNo(code);

                if (providerData == null) {
                    logger.warn("没有找到此卡号对应的浆员登记信息，不能进行操作...");
                    throw new AdscmSystemException("处理错误，没有找到此卡号对应的浆员登记信息，不能进行操作");
                }
            } else {
                logger.warn("没有卡号，不能进行操作...");
                throw new AdscmSystemException("处理错误，没有收到卡号，不能进行操作");
            }

            Date date = new Date();
            if ("BodyCall".equals(cmd)) {
                //呼叫体检
                logger.info("呼叫[" + code + "]体检");
                if (providerData.getBodyCheckCallTime() != null) {
                    date = providerData.getBodyCheckCallTime();
                }
                providerData.setBodyCheckCallTime(date);
                providerQueue.updateProviderData(providerData);
                MachineMgr.getInstance().sendMsgToAllotCtxs(BeanSupport.loadToAllotMsg(providerData, "body"));
            } else if ("BodyPass".equals(cmd)) {
                logger.info("[" + code + "]体检通过");
//                String nowDate = AdscmDateUtils.getNowOnlyDateFomat1(new Date());
                Wrapper<BodyCheck> wrapper = new EntityWrapper<>();
                wrapper.eq("registerNo", providerData.getRegisterNo());
                wrapper.eq("providerNo", providerData.getProviderId());
                List<BodyCheck> checkList = bodyCheckMapper.selectList(wrapper);
                if (checkList != null && checkList.size() > 0) {
                    BodyCheck bodyCheck = checkList.get(0);
                    if (bodyCheck.getBodyCheckResult() != null && AdscmBaseUtils.getInstance().isNotEmpty(bodyCheck.getBodyEndTime(), null)) {
                        //这两个不为null，才表示体检结束了
                        providerData.setBodyCheckId(bodyCheck.getBodyRecodeId());
                        providerData.setBodyCheckNo(bodyCheck.getBodyCheckNo());
                        boolean bodyIsPass = false;
                        if (bodyCheck.getBodyCheckResult() == 1) {
                            bodyIsPass = true;
                        }
                        providerData.setBodyIsPass(bodyIsPass);
                        providerData.setBodyCheckPassTime(AdscmDateUtils.parseDate(bodyCheck.getBodyEndTime()));
                        providerQueue.updateProviderData(providerData);

                        MachineMgr.getInstance().sendMsgToAllotCtxs(BeanSupport.loadToAllotMsg(providerData, null));

                    } else {
                        throw new AdscmSystemException("体检记录还未处理，不能进行【完成体检】操作");
                    }
                }
            } else if ("AssayCall".equals(cmd)) {
                logger.info("呼叫[" + code + "]化检");
                if (providerData.getAssayCallTime() != null) {
                    date = providerData.getAssayCallTime();
                }
                providerData.setAssayCallTime(date);
                providerQueue.updateProviderData(providerData);
                MachineMgr.getInstance().sendMsgToAllotCtxs(BeanSupport.loadToAllotMsg(providerData, "assay"));

            } else if ("AssayPass".equals(cmd)) {
                logger.info("[" + code + "]完成化检");
                Wrapper<PlasmaSamples> wrapper = new EntityWrapper<>();
                wrapper.eq("registerNo", providerData.getRegisterNo());
                wrapper.eq("providerNo", providerData.getProviderId());
                List<PlasmaSamples> list = plasmaSamplesMapper.selectList(wrapper);

                if (list != null && list.size() > 0) {

                    PlasmaSamples samples = list.get(0);
                    if (samples.getRecodeEndTime() != null && AdscmBaseUtils.getInstance().isNotEmpty(samples.getInspectionResult(), null)) {
                        providerData.setAssayId(samples.getRecodeNo());
                        providerData.setAssayPassTime(samples.getRecodeEndTime());
                        boolean assayIsPass = false;
                        if ("1".equals(samples.getInspectionResult())) {
                            assayIsPass = true;
                        }
                        providerData.setAssayIsPass(assayIsPass);

                        providerQueue.updateProviderData(providerData);

                        MachineMgr.getInstance().sendMsgToAllotCtxs(BeanSupport.loadToAllotMsg(providerData, null));
                    } else {
                        throw new AdscmSystemException("小样还未化检结束，不能进行【完成化检】操作");
                    }

                } else {
                    throw new AdscmSystemException("还没有采集小样，不能进行【完成化检】操作");
                }


            }


        } catch (Exception e) {
            logger.error("处理操作【" + code + "：" + cmd + "】异常", e);
            throw new AdscmSystemException("处理错误：" + e.getMessage());
        }
    }

    /**
     * 根据浆员身份证，获取这个浆员在本地磁盘上的建档照片和认证照片地址
     *
     * @param idCard
     * @param face
     * @return
     */
    @Override
    public String[] getImgsPath(String idCard, byte[] face) {


        String[] result = new String[2];

        try {

            if (idCard != null && !"".equals(idCard)) {
                //获取浆员基本信息
                Wrapper<ProviderInfo> providerInfoWrapper = new EntityWrapper<>();
                providerInfoWrapper.eq("idNo", idCard);
                List<ProviderInfo> providerInfos = providerInfoMapper.selectList(providerInfoWrapper);

                if (!(providerInfos.size() > 0)) {
                    providerInfoWrapper = new EntityWrapper<>();
                    providerInfoWrapper.eq("cardId", idCard);
                    providerInfos = providerInfoMapper.selectList(providerInfoWrapper);
                }
                if (providerInfos.size() > 0) {
                    ProviderInfo provider = providerInfos.get(0);
                    String soursePath = this.sourcePath + idCard + ".jpg";
                    File sourceFile = new File(soursePath);
                    if (!sourceFile.exists()) {
                        byte[] bytes = uploadService.downloadImageReturnBytes(provider.getPhoto());
//                        logger.info("将浆员【" + idCard + "】的建档照片写到照片源文件夹中...");
                        bytes = AdscmBaseUtils.getInstance().buildIcon(bytes, 180, 180);
                        AdscmBaseUtils.getInstance().writeFileToDisk(bytes, soursePath);
                    }

//                    logger.info("将获取到的浆员【" + idCard + "】的现场照片写到照片临时文件夹中...");
                    String tempPath = this.tempPath + idCard + ".jpg";
                    face = AdscmBaseUtils.getInstance().buildIcon(face, 180, 180);
                    AdscmBaseUtils.getInstance().writeFileToDisk(face, tempPath);

                    result[0] = soursePath;
                    result[1] = tempPath;

                }

            }
        } catch (Exception e) {
            logger.error("写入 【" + idCard + "】的照片到本地磁盘出现异常：" + e.getMessage());
        }


        return result;

    }

    /**
     * 生成小样记录，返回小样号
     *
     * @param bloodUser
     * @throws AdscmSystemException
     */
    @Override
    @Transactional
    public String  samlpeInsert(BloodUser bloodUser) throws AdscmSystemException {

        if (bloodUser != null && AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getId(), null)) {
        } else {
            throw new AdscmSystemException("参数错误");
        }

        ProviderData providerData = providerQueue.getByProviderNo(bloodUser.getId());
        if (providerData == null) {
            throw new AdscmSystemException("没有查询到该浆员当天的登记记录，请先登记...");
        } else if (!providerData.isNeedAssay()) {
            throw new AdscmSystemException("该浆员不需要采集小样...");
        }

        Wrapper<ProviderInfo> providerInfoWrapper = new EntityWrapper<>();
        providerInfoWrapper.eq("cardId", bloodUser.getId());
        List<ProviderInfo> providerInfos = providerInfoMapper.selectList(providerInfoWrapper);
        ProviderInfo providerInfo = null;
        if (CollectionUtils.isNotEmpty(providerInfos) && providerInfos.size() > 0) {
            providerInfo = providerInfos.get(0);
        } else {
            throw new AdscmSystemException("没有查到该浆员的建档信息");
        }

        PlasmaSamples plasmaSamples = new PlasmaSamples();
        Wrapper<PlasmaSamples> plasmaSamplesWrapper = new EntityWrapper<>();
        plasmaSamplesWrapper.eq("providerNo", providerInfo.getId()).eq("registerNo", providerData.getRegisterNo());
        List<PlasmaSamples> samples = plasmaSamplesMapper.selectList(plasmaSamplesWrapper);

        if (samples != null && samples.size() > 0) {
            logger.info("已经采集小样了...");
            return samples.get(0).getSampleNo();
        }


//        plasmaSamples.setProviderNo(String.valueOf(providerInfos.get(0).getId()));
//        Wrapper<PlasmaSamples> plasmaSamplesWrapper = new EntityWrapper<>();
//        if (AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getNurseId(), null)) {
//            plasmaSamples.setCreateNurse(bloodUser.getNurseId());
//        } else {
//            throw new AdscmSystemException("护士id不能为空");
//        }
//        plasmaSamplesWrapper = new EntityWrapper<>();
////                查询今天或者明天有没有该献浆员的小样化检记录
//        plasmaSamplesWrapper.eq("providerNo", providerInfos.get(0).getId()).
//                like("recodeTime", AdscmDateUtils.getTodayAndTomorrow(new Date())[0])
//                .or().like("recodeTime", AdscmDateUtils.getTodayAndTomorrow(new Date())[1]);
//        List<PlasmaSamples> samplesList = plasmaSamplesMapper.selectList(plasmaSamplesWrapper);
//        if (samplesList.size() == 0) {

        int smallNum = 1;
        String maxSampleNo = plasmaSamplesMapper.getMaxSampleOnDay(AdscmDateUtils.getNowOnlyDateFomat2(new Date()));
        if (AdscmBaseUtils.getInstance().isNotEmpty(maxSampleNo,null)){
            smallNum = Integer.valueOf(maxSampleNo.substring(maxSampleNo.length() - 4)) + 1;
        }

//        int smallNum = 1;
//        plasmaSamplesWrapper = new EntityWrapper<>();
//        plasmaSamplesWrapper.like("recodeTime", AdscmDateUtils.getTodayAndTomorrow(new Date())[0]).and().eq("sampleType","1");
//        plasmaSamplesWrapper.orderBy("sampleNo", false);
//        plasmaSamplesWrapper.last("limit 1");
//        samples = plasmasamplesmapper.selectList(plasmaSamplesWrapper);
//        String sampleNo = null;
//        if (samples.size() > 0) {
//            sampleNo = samples.get(0).getSampleNo();
//            smallNum = Integer.valueOf(sampleNo.substring(sampleNo.length() - 4));
//            smallNum = smallNum + 1;
//        }
        NumberFormat numberFormat = new DecimalFormat("0000");
        String sampleNo = AdscmDateUtils.getNowOnlyDateFomat2(new Date()) + numberFormat.format(smallNum);
        plasmaSamples.setSampleNo(sampleNo);
        plasmaSamples.setSamplePhoto(uploadService.uploadImageByBytes(bloodUser.getPhoto()));
        plasmaSamples.setName(bloodUser.getName());
        plasmaSamples.setIdNo(bloodUser.getIdNumber());
        plasmaSamples.setInspectionStatus(0);
        plasmaSamples.setBloodType(providerInfo.getBloodType());
        plasmaSamples.setRecodeStatus(0);
        plasmaSamples.setSampleType(1);
        plasmaSamples.setGatheringPlace(0);
        plasmaSamples.setGatheringTime(new Date());
        plasmaSamples.setThreshold(String.valueOf(bloodUser.getThreshold()));
        plasmaSamples.setAuthMethod(bloodUser.getRzfs());
        plasmaSamples.setCreateNurse(bloodUser.getNurseId());
        plasmaSamples.setProviderNo(providerData.getProviderId()+"");
        plasmaSamples.setRegisterNo(providerData.getRegisterNo());
        plasmaSamples.setRecodeTime(new Date());
        plasmaSamples.setSYNDATE(AdscmDateUtils.getNowOnlyDateFomat1(new Date()));
        plasmaSamples.setMODIFY_TIME(AdscmDateUtils.getDateFomat(new Date()));
        plasmaSamplesMapper.insert(plasmaSamples);


//        ProviderData providerData = new ProviderData();
//        providerData.setProviderId(providerInfos.get(0).getId());
        providerData.setAssayCallTime(new Date());
        providerData.setCurrentStatus(4);
        providerDataMapper.updateById(providerData);
        MachineMgr.getInstance().sendMsgToAllotCtxs(BeanSupport.loadToAllotMsg(providerData, "assay"));
//        }


        return plasmaSamples.getSampleNo();
    }




    @Transactional
    @Override
    public ProviderHeat updateHeat(BloodUser bloodUser) throws AdscmSystemException {
        ProviderData providerData = null;
        if (bloodUser != null && AdscmBaseUtils.getInstance().isNotEmpty(bloodUser.getId(),null)){
            providerData = providerQueue.getByProviderNo(bloodUser.getId());
            if(providerData == null){
                throw new AdscmSystemException("没有查询到该浆员当天的登记信息");
            }
        }else {
            throw new AdscmSystemException("参数异常");
        }

        Wrapper<HeatSeal> heatSealWrapper=new EntityWrapper<>();;
        heatSealWrapper.eq("providerNo",providerData.getProviderNo())
                .like("createTime",AdscmDateUtils.getTodayAndTomorrow(new Date())[0]);
        List<HeatSeal> heatSeals = heatSealMapper.selectList(heatSealWrapper);//根据贡浆者id查询和时间查询热合生成记录
        HeatSeal heatSeal=new HeatSeal();
        ProviderHeat providerHeat=new ProviderHeat();
        if (CollectionUtils.isEmpty(heatSeals)){
            throw new AdscmSystemException("热合记录未生成");
        }else {
            providerHeat.setHid(String.valueOf(heatSeals.get(0).getSealId()));
            heatSeal.setSealId(heatSeals.get(0).getSealId());
            heatSealWrapper=new EntityWrapper<>();;
            heatSealWrapper.orderBy("createTime",false);
            heatSealWrapper.last("limit 1");
            List<HeatSeal> heatSealList = heatSealMapper.selectList(heatSealWrapper);//根据日期排序查询血浆编码最大值
            heatSeal.setCreateTime(new Date());
            heatSeal.setProviderNo(String.valueOf(providerData.getProviderId()));
            heatSeal.setCreateNurse(bloodUser.getNurseId());
            heatSeal.setRegisterNo(providerData.getRegisterNo());
            heatSeal.setPlasmaBagPhoto(uploadService.uploadImageByBytes(bloodUser.getPhoto()));
            if (CollectionUtils.isEmpty(heatSealList)){
                Wrapper<BoxConf> boxConfWrapper=new EntityWrapper<>();
                boxConfWrapper.orderBy("createTime",false);
                boxConfWrapper.last("limit 1");
                List<BoxConf> boxList = boxConfMapper.selectList(boxConfWrapper);//查询血浆编码配置表
                if (CollectionUtils.isEmpty(boxList)){
                    throw new AdscmSystemException("没有配置血浆编码表");
                }else {
                    heatSeal.setPlasmaNo(boxList.get(0).getPlasmaStartNo());
                    heatSeal.setBoxNo(boxList.get(0).getBoxEndNo());
                }
            }else {
                Wrapper<BoxConf> boxConfWrapper=new EntityWrapper<>();
                boxConfWrapper.orderBy("createTime",false);
                boxConfWrapper.last("limit 1");
                List<BoxConf> boxList = boxConfMapper.selectList(boxConfWrapper); //查询血浆站的代码
                String year=heatSealList.get(0).getPlasmaNo().substring(3,5);
                String boxNo=heatSealList.get(0).getPlasmaNo().substring(6,12);
                String num=heatSealList.get(0).getPlasmaNo().substring(12);
                String date=String.valueOf(AdscmDateUtils.getTheYear(new Date())).substring(2);
                String jzcode=boxList.get(0).getJzCode();
                if (year.equals(date)){
                    year=year;
                }else {
                    year=date;
                }
                NumberFormat numberFormat = new DecimalFormat("000000");
                if (Integer.valueOf(num)>30){
                    boxNo=numberFormat.format(Integer.valueOf(boxNo)+1);
                    num="01";
                }else {
                    boxNo=boxNo;
                    numberFormat = new DecimalFormat("00");
                    num=numberFormat.format(Integer.valueOf(num)+1);
                }
                heatSeal.setBoxNo(boxNo);
                heatSeal.setPlasmaNo(jzcode+year+"P"+boxNo+num);
            }

        }
        Integer integer = heatSealMapper.updateById(heatSeal);

        Wrapper<ProviderCollection> providerCollectionWrapper=new EntityWrapper<>();
        providerCollectionWrapper.eq("providerNo",providerData.getProviderNo());
        providerCollectionWrapper.eq("startTime",AdscmDateUtils.getTodayAndTomorrow(new Date())[0]);
        List<ProviderCollection> collectionList = providerCollectionMapper.selectList(providerCollectionWrapper);//查询献血浆记录
        if (CollectionUtils.isEmpty(collectionList)){
            throw new AdscmSystemException("没有查到献血浆记录");
        }else {
            providerHeat.setPz(collectionList.get(0).getInitWeight());
            providerHeat.setNums(collectionList.get(0).getTotalBloodNum());
        }
        ProviderInfo providerInfo = providerInfoMapper.selectById(providerData.getProviderId());
        providerHeat.setCardid(providerData.getProviderNo());
        providerHeat.setName(providerData.getName());
        providerHeat.setXb(providerData.getSex());
        providerHeat.setXjbh(heatSeal.getPlasmaNo());
        if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getPlasmaType(),null)){
            providerHeat.setXjlx(String.valueOf(providerInfo.getPlasmaType()));
        }

        return providerHeat;
    }

    /**
     * 查询浆员基本信息
     * @param idCard
     * @return
     * @throws AdscmSystemException
     */
    @Override
    public BloodUser queryProviderInfo(String idCard) throws AdscmSystemException {
        BloodUser bloodUser=new BloodUser();
        if (!AdscmBaseUtils.getInstance().isNotEmpty(idCard,null)){
            throw new AdscmSystemException("身份证或卡号为空");
        }
        Wrapper<ProviderInfo> providerInfoWrapper =new EntityWrapper<>();
        providerInfoWrapper.eq("idNo",idCard);
        List<ProviderInfo> providerInfos = providerInfoMapper.selectList(providerInfoWrapper);
        //根据身份证查询
        if (providerInfos!=null&&providerInfos.size()>0){
            ProviderInfo providerInfo = providerInfos.get(0);
            bloodUser.setId(providerInfo.getCardId());//设置卡号
            bloodUser.setName(providerInfo.getName());
            if ("1".equals(providerInfo.getSex())){
                bloodUser.setSex("男");
            }
            if ("2".equals(providerInfo.getSex())){
                bloodUser.setSex("女");
            }
            bloodUser.setNationality(AdscmBaseUtils.getInstance().getNation(providerInfo.getNation()));
            bloodUser.setBirthday(providerInfo.getBirthday());
            bloodUser.setAddress(providerInfo.getAddress());
            bloodUser.setAge(AdscmDateUtils.getAge(providerInfo.getBirthday()));
            byte[] bytes = uploadService.downloadImageReturnBytes(providerInfo.getPhoto());
            bloodUser.setPhoto(bytes);
        }else {
            Wrapper<ProviderInfo> providerInfoByCardIdWrapper =new EntityWrapper<>();
            providerInfoByCardIdWrapper.eq("cardId",idCard);
            List<ProviderInfo> providerInfoByCardIds = providerInfoMapper.selectList(providerInfoByCardIdWrapper);
            if (providerInfoByCardIds!=null&&providerInfoByCardIds.size()>0){
                ProviderInfo providerInfo = providerInfoByCardIds.get(0);
                bloodUser.setId(providerInfo.getCardId());//设置卡号
                bloodUser.setName(providerInfo.getName());
                if ("1".equals(providerInfo.getSex())){
                    bloodUser.setSex("男");
                }
                if ("2".equals(providerInfo.getSex())){
                    bloodUser.setSex("女");
                }
                bloodUser.setNationality(AdscmBaseUtils.getInstance().getNation(providerInfo.getNation()));
                bloodUser.setBirthday(providerInfo.getBirthday());
                bloodUser.setAddress(providerInfo.getAddress());
                bloodUser.setAge(AdscmDateUtils.getAge(providerInfo.getBirthday()));
                byte[] bytes = uploadService.downloadImageReturnBytes(providerInfo.getPhoto());
                bloodUser.setPhoto(bytes);
            }else {
                throw new AdscmSystemException("没查询此浆员信息");
            }
        }
        return bloodUser;
    }

    @Override
    public CostInfo providerCost(CostInfo costInfo) throws AdscmSystemException {
        if (!AdscmBaseUtils.getInstance().isNotEmpty(costInfo,null)){
            throw  new  AdscmSystemException("信息为空");
        }
        //根据卡号查询浆员缓存个人信息
        if (!AdscmBaseUtils.getInstance().isNotEmpty(costInfo.getCardid(),null)){
            throw  new  AdscmSystemException("浆员卡号信息不存在");
        }
        ProviderData providerData = providerQueue.getByProviderNo(costInfo.getCardid());
        if (!AdscmBaseUtils.getInstance().isNotEmpty(providerData,null)){
            throw  new  AdscmSystemException("没有查询到浆员当天的登记记录");
        }
        ProviderInfo providerInfo = providerInfoMapper.selectById(providerData.getProviderId());
        if (!AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
            throw  new  AdscmSystemException("浆员基本信息未找到");
        }
        Wrapper<ProviderCost> providerCostWrapper=new EntityWrapper<>();
        providerCostWrapper.eq("providerNo",providerInfo.getId());
        providerCostWrapper.eq("registerNo",providerData.getRegisterNo());
        List<ProviderCost> providerCosts = providerCostMapper.selectList(providerCostWrapper);
        if (providerCosts!=null&&providerCosts.size()>0){
            ProviderCost providerCost = providerCosts.get(0);
            if ("1".equals(providerCost.getState())){
                //费用已经发放
                throw  new  AdscmSystemException("费用已经发放");
            }else {


                if (!AdscmBaseUtils.getInstance().isNotEmpty(costInfo.getType(),null)){
                    throw  new  AdscmSystemException("请求类型为空");
                }
                if ("0".equals(costInfo.getType())){
                    //查询费用信息
                    //查询采浆记录
                    ProviderCollection providerCollection = providerCollectionMapper.selectById(providerCost.getCollectionId());
                    if (!AdscmBaseUtils.getInstance().isNotEmpty(providerCollection,null)){
                        throw  new  AdscmSystemException("根据费用记录没有查询到采浆记录");
                    }
                    if (new Date().getTime()-providerCollection.getEndTime().getTime()<600000){
                        throw  new  AdscmSystemException("献浆后未到15分钟不能领取费用");
                    }
                    costInfo.setCardid(providerInfo.getCardId());
                    costInfo.setXm(providerInfo.getName());
                    costInfo.setCjl(providerCollection.getTotalPlasmaNum().toString());
                    costInfo.setCjrq(  AdscmDateUtils.getNowOnlyDateFomat1(providerCollection.getCollectionDate()));
                    costInfo.setWgf(providerCost.getBaseMoney().toString());
                    costInfo.setCfbz(providerCost.getTrafficFee().toString());
                    costInfo.setHj(providerCost.getPutOutMoney().toString());
                    JyUser jyUser = jyUserMapper.selectById(providerCollection.getNurse());
                    if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser,null)){
                        costInfo.setCjhs(jyUser.getName());
                    }else {
                        costInfo.setCjhs(providerCollection.getNurse());
                    }
                    costInfo.setTimesAllowance(providerCost.getTimesAllowance().toString());
                    costInfo.setCollectionTime(providerCost.getCollectionTimes().toString());
                }
                if ("1".equals(costInfo.getType())){
                    //保存费用信息
                    //查询今日最大的发放序号
                    String  costIdx="";
                    String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
                    Wrapper<ProviderCost> getMaxIdxwrapper= new EntityWrapper<>();
                    getMaxIdxwrapper.like("costIdx",today, SqlLike.RIGHT);
                    getMaxIdxwrapper.orderBy("costIdx",false);
                    List<ProviderCost> getMaxIdxProviderCosts = providerCostMapper.selectList(getMaxIdxwrapper);
                    if (getMaxIdxProviderCosts!=null && getMaxIdxProviderCosts.size()>0){
                        ProviderCost getMaxIdxProviderCost = getMaxIdxProviderCosts.get(0);
                        costIdx= getMaxIdxProviderCost.getCostIdx();
                        costIdx=  String.valueOf(Long.valueOf(costIdx)+1) ;
                    }else {
                        costIdx=  today+ "0001";
                    }
                    providerCost.setCostIdx(costIdx);
                    providerCost.setPutOutDate(AdscmDateUtils.getFormateDate(new Date()));
                    providerCost.setPutOutStartTime(AdscmDateUtils.parseDateL(costInfo.getCrstime()));
                    providerCost.setPutOutEndTime(AdscmDateUtils.parseDateL(costInfo.getCretime()));
                    String photoPath = uploadService.uploadImageByBytes(costInfo.getPhoto());
                    providerCost.setPhoto(photoPath);
                    providerCost.setThreshold(Float.valueOf(costInfo.getCm()));
                    providerCost.setState("1");
                    providerCost.setEndTime(new Date());
                    providerCost.setIssuePlace("2");
                    providerCost.setIssueType("2");
                    providerCost.setRzfs(costInfo.getRzfs());
                    providerCost.setPutWorker(costInfo.getNurseid());
                    providerCost.setModifyTime(new Date());
                    providerCost.setSynDate(AdscmDateUtils.getFormateDate(new Date()));
                    providerCostMapper.updateById(providerCost);
                    costInfo.setResult("成功修改");
                }

            }

        }else {
            throw new AdscmSystemException("没查找到浆员费用信息");
        }

        return costInfo;
    }


    @Override
    public void freeMachineByProvider(String code) throws AdscmSystemException {
        if (!AdscmBaseUtils.getInstance().isNotEmpty(code,null)){
            throw new AdscmSystemException("参数错误");
        }
        ProviderData provider = providerQueue.getByProviderNo(code);
        if (!AdscmBaseUtils.getInstance().isNotEmpty(provider,"providerId")){
            throw new AdscmSystemException("浆员未登记");
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(provider,"machineCode")){
            throw new AdscmSystemException("没有分配设备！");
        }

        MachineData machine = MachineMgr.getInstance().getMachine(provider.getMachineCode());
        if ((machine.getRunStatus() >= 7) && (machine.getRunStatus() <= 13)) {
            throw new AdscmSystemException("已开始采浆，不能放弃！");
        }


        provider.setAllotCall(false);
        provider.setMachineCode(null);
        provider.setAllotTime(null);
        provider.setCollectStartTime(null);
        provider.setMachineCode(null);


        if (machine != null) {
            doCancelDonor(provider, machine);
        }

        if (machine != null) {
            machine.doFree();
        }

        providerQueue.updateProviderData(provider);

        //发送给分配机
        MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(provider,null));
        MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(machine));
//        this.sendAllotMacInfo(machine.getCode());
        MachineMgr.getInstance().updateRedisMachineData(objectRedisTemplate,machine);

    }


    private void doCancelDonor(ProviderData provider, MachineData allotmachine) throws AdscmSystemException {

         boolean isSucessed = MachineMgr.getInstance().sendCancelDonor(allotmachine.getCode(),provider.getProviderNo(),provider.getRegisterNo());

         if (!isSucessed){
             throw new AdscmSystemException("取消分配失败，请稍后再试...");
         }

    }


    @Override
    public void doFreeMachine(String mcode) throws AdscmSystemException {

        if (!AdscmBaseUtils.getInstance().isNotEmpty(mcode,null)){
            throw new AdscmSystemException("参数错误");
        }

        MachineMgr.getInstance().doFreeMachine(mcode);
        MachineData machine = MachineMgr.getInstance().getMachine(mcode);
        MachineMgr.getInstance().updateRedisMachineData(objectRedisTemplate,machine);
    }
}
